﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using ExperimentUpon.Util;
using ExperimentUpon.VO;
using NHibernate.Criterion;
using ExperimentUpon.Service.Exception;

namespace ExperimentUpon.Service.Impl
{
    public class UserServiceImpl : IUserService
    {
        public User login(string account, string password)
        {
            ISession session = NHibernateUtils.OpenSession();
            session.BeginTransaction();
            IList<User> userList = null;
            try
            {
                userList = session.CreateCriteria(typeof(User))
                    .Add(Expression.Eq("Account", account)).List<User>();
                session.Transaction.Commit();
            }
            catch (System.Exception e)
            {
                session.Transaction.Rollback();
                throw new BaseException(e.Message, e);
            }
            finally
            {
                session.Close();
            }
            if (null == userList || 1 != userList.Count)
            {
                throw new UserException(Key.Exception.AccountError);
            }
            User user = userList[0];
            if(!password.Equals(user.Password))
            {
                throw new UserException(Key.Exception.PasswordError);
            }
            return user;
        }
    }
}
